package com.example.transactional.config.dynamicDataSource;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class DynamicDataSourceAspect {

    /**
     * 使用从库查询
     */
    @Pointcut("execution(* com.example.transactional.service..*.select*(..)) " +
            "|| execution(* com.example.transactional.service..*.list*(..)) " +
            "|| execution(* com.example.transactional.service..*.query*(..)) " +
            "|| execution(* com.example.transactional.service..*.find*(..)) " +
            "|| execution(* com.example.transactional.service..*.get*(..))")
    public void readPointcut() {

    }

    /**
     * 使用主库插入更新
     */
    @Pointcut("execution(* com.example.transactional.service..*.insert*(..)) " +
            "|| execution(* com.example.transactional.service..*.save*(..)) " +
            "|| execution(* com.example.transactional.service..*.update*(..)) " +
            "|| execution(* com.example.transactional.service..*.edit*(..)) " +
            "|| execution(* com.example.transactional.service..*.delete*(..)) " +
            "|| execution(* com.example.transactional.service..*.remove*(..))")
    public void writePointcut() {

    }

    @Before("readPointcut()")
    public void read() {
        DynamicDataSourceHolder.setDBType(DynamicDataSourceHolder.DB_SLAVE);
    }

    @Before("writePointcut()")
    public void write() {
        DynamicDataSourceHolder.setDBType(DynamicDataSourceHolder.DB_MASTER);
    }

}
